{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Executed in 42.450190 ms\n"
     ]
    }
   ],
   "source": [
    "from time import time\n",
    "\n",
    "start_time = time()\n",
    "\n",
    "for _ in range(1000000):\n",
    "    pass\n",
    "\n",
    "time_taken = (time() - start_time) * 1000\n",
    "\n",
    "print('Executed in %f ms' % time_taken)\n",
    "\n",
    "assert(time_taken > 0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "context = {}\n",
    "\n",
    "context['symbols'] = [\n",
    "    'BP',\n",
    "    'CD',\n",
    "    'CL',\n",
    "    'ED',\n",
    "    'GC',\n",
    "    'HG',\n",
    "    'HO',\n",
    "    'HU',\n",
    "    'JY',\n",
    "    'SB',\n",
    "    'SF',\n",
    "    'SP',\n",
    "    'SV',\n",
    "    'TB',\n",
    "    'TY',\n",
    "    'US'\n",
    "]\n",
    "\n",
    "assert(len(context['symbols']) == 16)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from quantopian.research.experimental import continuous_future\n",
    "\n",
    "context['markets'] = map(\n",
    "    lambda market: continuous_future(market),\n",
    "    context['symbols']\n",
    ")\n",
    "\n",
    "assert(len(context['markets']) == 16)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('BP', Timestamp('2017-05-23 00:00:00+0000', tz='UTC'))\n",
      "('CD', Timestamp('2017-05-23 00:00:00+0000', tz='UTC'))\n",
      "('CL', Timestamp('2017-05-23 00:00:00+0000', tz='UTC'))\n",
      "('ED', Timestamp('2017-05-23 00:00:00+0000', tz='UTC'))\n",
      "('GC', Timestamp('2017-05-23 00:00:00+0000', tz='UTC'))\n",
      "('HG', Timestamp('2017-05-23 00:00:00+0000', tz='UTC'))\n",
      "('HO', Timestamp('2017-05-23 00:00:00+0000', tz='UTC'))\n",
      "('HU', Timestamp('2006-12-29 00:00:00+0000', tz='UTC'))\n",
      "('JY', Timestamp('2017-05-23 00:00:00+0000', tz='UTC'))\n",
      "('SB', Timestamp('2017-05-23 00:00:00+0000', tz='UTC'))\n",
      "('SF', Timestamp('2017-05-23 00:00:00+0000', tz='UTC'))\n",
      "('SP', Timestamp('2017-05-23 00:00:00+0000', tz='UTC'))\n",
      "('SV', Timestamp('2017-05-23 00:00:00+0000', tz='UTC'))\n",
      "('TB', Timestamp('2003-09-15 00:00:00+0000', tz='UTC'))\n",
      "('TY', Timestamp('2017-05-23 00:00:00+0000', tz='UTC'))\n",
      "('US', Timestamp('2017-05-23 00:00:00+0000', tz='UTC'))\n"
     ]
    }
   ],
   "source": [
    "for market in context['markets']:\n",
    "    print(market.root_symbol, market.end_date)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from quantopian.research.experimental import history\n",
    "\n",
    "fields = ['high', 'low', 'close_price']\n",
    "start_date = '2017-02-27'\n",
    "end_date = '2017-03-31'\n",
    "frequency = 'daily'\n",
    "\n",
    "context['prices'] = history(\n",
    "    context['markets'],\n",
    "    fields=fields,\n",
    "    frequency=frequency,\n",
    "    start_date=start_date,\n",
    "    end_date=end_date\n",
    ")\n",
    "\n",
    "assert(context['prices'].shape == (3, 25, 16))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "context['prices'].dropna(axis=2, inplace=True)\n",
    "\n",
    "assert(context['prices'].shape == (3, 25, 14))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "if len(context['prices'].items) == len(fields):\n",
    "    context['prices'] = context['prices'].transpose(2, 1, 0)\n",
    "    context['prices'] = context['prices'].reindex()\n",
    "\n",
    "assert(context['prices'].shape == (14, 25, 3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from talib import ATR\n",
    "\n",
    "context['average_true_range'] = {}\n",
    "\n",
    "rolling_window = 21\n",
    "moving_average = 20\n",
    "\n",
    "for market in context['prices'].items:\n",
    "    context['average_true_range'][market] = ATR(\n",
    "        context['prices'][market].high[-rolling_window:],\n",
    "        context['prices'][market].low[-rolling_window:],\n",
    "        context['prices'][market].close_price[-rolling_window:],\n",
    "        timeperiod=moving_average\n",
    "    )[-1]\n",
    "\n",
    "assert(len(context['average_true_range']) == 14)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "fields = ['contract']\n",
    "start_date = '2017-03-31'\n",
    "end_date = '2017-03-31'\n",
    "\n",
    "context['contracts'] = history(\n",
    "    context['markets'],\n",
    "    fields=fields,\n",
    "    frequency=frequency,\n",
    "    start_date=start_date,\n",
    "    end_date=end_date\n",
    ")\n",
    "\n",
    "assert(context['contracts'].shape == (1, 1, 16))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "if len(context['contracts'].items) == len(fields):\n",
    "    context['contracts'] = context['contracts'].transpose(2, 1, 0)\n",
    "    context['contracts'] = context['contracts'].reindex()\n",
    "\n",
    "assert(context['contracts'].shape == (16, 1, 1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(u'BPM17', 0.0001, 62500.0, Timestamp('2017-06-15 00:00:00+0000', tz='UTC'))\n",
      "(u'CDM17', 0.0001, 100000.0, Timestamp('2017-06-16 00:00:00+0000', tz='UTC'))\n",
      "(u'CLK17', 0.01, 1000.0, Timestamp('2017-04-18 00:00:00+0000', tz='UTC'))\n",
      "(u'EDJ17', 0.005, 2500.0, Timestamp('2017-04-12 00:00:00+0000', tz='UTC'))\n",
      "(u'GCM17', 0.1, 100.0, Timestamp('2017-05-29 00:00:00+0000', tz='UTC'))\n",
      "(u'HGK17', 0.0005, 25000.0, Timestamp('2017-04-26 00:00:00+0000', tz='UTC'))\n",
      "(u'HOK17', 0.0001, 42000.0, Timestamp('2017-04-26 00:00:00+0000', tz='UTC'))\n",
      "(u'JYM17', 5e-07, 12500000.0, Timestamp('2017-06-15 00:00:00+0000', tz='UTC'))\n",
      "(u'SBK17', 0.0001, 112000.0, Timestamp('2017-04-26 00:00:00+0000', tz='UTC'))\n",
      "(u'SFM17', 0.0001, 125000.0, Timestamp('2017-06-15 00:00:00+0000', tz='UTC'))\n",
      "(u'SPM17', 0.1, 250.0, Timestamp('2017-06-13 00:00:00+0000', tz='UTC'))\n",
      "(u'SVK17', 0.005, 5000.0, Timestamp('2017-04-26 00:00:00+0000', tz='UTC'))\n",
      "(u'TYM17', 0.015625, 1000.0, Timestamp('2017-05-29 00:00:00+0000', tz='UTC'))\n",
      "(u'USM17', 0.03125, 1000.0, Timestamp('2017-05-29 00:00:00+0000', tz='UTC'))\n"
     ]
    }
   ],
   "source": [
    "for market in context['contracts']:\n",
    "    contract = context['contracts'][market].contract[0]\n",
    "    \n",
    "    if contract is not None:\n",
    "        print(\n",
    "            contract.symbol,\n",
    "            contract.tick_size,\n",
    "            contract.multiplier,\n",
    "            contract.auto_close_date\n",
    "        )\n",
    "        \n",
    "        if contract.symbol == 'USM17':\n",
    "            assert(contract.tick_size == 0.03125)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('BP', 640.62499999999739)\n",
      "('CD', 430.00000000000034)\n",
      "('CL', 1244.1000000000008)\n",
      "('ED', 51.249999999997797)\n",
      "('GC', 1224.3899999999962)\n",
      "('HG', 1207.5000000000002)\n",
      "('HO', 1423.7999999999979)\n",
      "('JY', 0.0)\n",
      "('SB', 582.39999999999986)\n",
      "('SF', 818.75000000000421)\n",
      "('SP', 3884.8124999999809)\n",
      "('SV', 1315.0000000000048)\n",
      "('TY', 487.39999999999884)\n",
      "('US', 1188.9500000000025)\n"
     ]
    }
   ],
   "source": [
    "for market in context['contracts']:\n",
    "    contract = context['contracts'][market].contract[0]\n",
    "    \n",
    "    if contract is not None:\n",
    "        dollar_volatility = contract.multiplier * context['average_true_range'][market]\n",
    "        \n",
    "        print(market.root_symbol, dollar_volatility)\n",
    "        \n",
    "        if market.root_symbol == 'HO':\n",
    "            assert(dollar_volatility == 1423.7999999999979)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Trade size: 6\n"
     ]
    }
   ],
   "source": [
    "context['capital_risk_per_trade'] = 0.01\n",
    "context['starting_cash'] = 1000000\n",
    "# context['portfolio_value'] = 1100000\n",
    "context['portfolio_value'] = 900000\n",
    "context['capital_multiplier'] = 2\n",
    "\n",
    "profit = context['portfolio_value'] - context['starting_cash']\n",
    "context['cash'] = context['starting_cash']\n",
    "\n",
    "if profit < 0:\n",
    "    context['cash'] = context['starting_cash'] + profit * context['capital_multiplier']\n",
    "\n",
    "capital_per_trade = context['cash'] * context['capital_risk_per_trade']\n",
    "trade_size = capital_per_trade / dollar_volatility\n",
    "\n",
    "print('Trade size: %i' % int(trade_size))\n",
    "\n",
    "assert(int(trade_size) == 6)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "context['twenty_day_breakout'] = 20\n",
    "context['fifty_five_day_breakout'] = 55"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('BP', 1.256)\n",
      "('CD', 0.752)\n",
      "('CL', 50.850000000000001)\n",
      "('ED', 98.709999999999994)\n",
      "('GC', 1251.5999999999999)\n",
      "('HG', 2.6560000000000001)\n",
      "('HO', 1.577)\n",
      "('JY', 0.0089999999999999993)\n",
      "('SB', 0.16800000000000001)\n",
      "('SF', 1.002)\n",
      "('SP', 2358.4000000000001)\n",
      "('SV', 18.274999999999999)\n",
      "('TY', 124.625)\n",
      "('US', 150.96899999999999)\n"
     ]
    }
   ],
   "source": [
    "for market in context['prices'].items:\n",
    "    print(market.root_symbol, context['prices'][market].close_price[-1])\n",
    "    \n",
    "    if market.root_symbol == 'SF':\n",
    "        assert(context['prices'][market].close_price[-1] == 1.002)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "context['twenty_day_high'] = {}\n",
    "context['twenty_day_low'] = {}\n",
    "\n",
    "for market in context['prices'].items:\n",
    "    context['twenty_day_high'][market] = context['prices'][market]\\\n",
    "        .high[-context['twenty_day_breakout']-1:-1].max()\n",
    "        \n",
    "    context['twenty_day_low'][market] = context['prices'][market]\\\n",
    "        .low[-context['twenty_day_breakout']-1:-1].min()\n",
    "    \n",
    "    if market.root_symbol == 'BP':\n",
    "        assert(context['prices'][market].high[-context['twenty_day_breakout']-1:-1].min() == 1.222)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "context['fifty_five_day_high'] = {}\n",
    "context['fifty_five_day_low'] = {}\n",
    "\n",
    "for market in context['prices'].items:\n",
    "    context['fifty_five_day_high'][market] = context['prices'][market]\\\n",
    "        .high[-context['fifty_five_day_breakout']-1:-1].max()\n",
    "        \n",
    "    context['fifty_five_day_low'][market] = context['prices'][market]\\\n",
    "        .low[-context['fifty_five_day_breakout']-1:-1].min()\n",
    "    \n",
    "    if market.root_symbol == 'GC':\n",
    "        assert(context['prices'][market].high[-context['fifty_five_day_breakout']-1:-1].max() == 1268.337)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}